<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/26
 * Time: 14:23
 */

namespace app\admin\controller;


use app\admin\logic\TopicLogic;
use app\common\controller\Backend;
use think\Controller;
use think\Db;
use think\Exception;

/**
 * 题库管理
 * Class Topic
 * @package app\admin\controller
 */
class Topic extends Backend
{
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Topic');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>&$value){
                $value['category_name'] = model('Category')->where(array('id'=>$value['category_id']))->value('name');
                $value['sub_category_name'] = model('Category')->where(array('id'=>$value['sub_category_id']))->value('name');
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $data = $this->request->post('data/a');
            if($data){
                $logic = new TopicLogic();
                $result = $logic->add($data);
                $msg = '';
                $success = false;
//                $result = collection($result)->toArray();
//                $this->error($msg,null,$result);
                $rtnData = array();
                switch($result['status']){
                    case 0:
                        $rtnData = $result['error'];
                        $msg = '添加失败！';
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if($success){
                    $this->success('添加成功！');
                }else{
                    $this->error($msg,'',$rtnData);
                }
            }else{
                $this->error();
            }
        }
        return $this->view->fetch();
    }


    /**
     * ajax获取题目信息
     */
    public function getTopic(){
        $id = $this->request->get("id");
        $topic = $topic = $this->getTopicById($id);
//        $this->ajaxReturn(json_encode($topic),'JSON');
        echo json_encode($topic);
    }

    private function getTopicById($id){
        $topic = $this->model->where(['id'=>$id])->find();
        if($topic) {
            $option_items = model('Option')->where(['topic_id' => $topic['id']])->select();
            $topic['option_items'] = $option_items;
        }
        return $topic;
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
//        $row = $this->model->get(['id' => $ids]);
//        if (!$row)
//            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $data = $this->request->post('data/a');
            if($data){
                $logic = new TopicLogic();
                $result = $logic->edit($data);
                $msg = '';
                $success = false;
//                $result = collection($result)->toArray();
//                $this->error($msg,null,$result);
                $rtnData = array();
                switch($result['status']){
                    case 0:
                        $rtnData = $result['error'];
                        $msg = '修改失败！';
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if($success){
                    $this->success('修改成功！');
                }else{
                    $this->error($msg,'',$rtnData);
                }
            }else{
                $this->error();
            }
            $this->error();
        }
        $row = model('Topic')->where(array('id'=>$ids))->field('grade,is_use')->find();
        $this->view->assign('row',$row);
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 批量上架
     */
    public function shelves(){
        Db::startTrans();
        try {
            $ids = $this->request->post('topic_ids/a');
            model('Topic')->where('id','in',$ids)->setField('is_use',1);
            Db::commit();
            $this->success('上架成功！');
        }catch (Exception $e){
            Db::rollback();
            $this->error('上架失败！','',$e->getMessage());
        }
    }

    /**
     * 批量下架
     */
    public function the_shelves(){
        Db::startTrans();
        try {
            $ids = $this->request->post('topic_ids/a');
            model('Topic')->where('id','in',$ids)->setField('is_use',0);
            Db::commit();
            $this->success('下架成功！');
        }catch (Exception $e){
            Db::rollback();
            $this->error('下架失败！','',$e->getMessage());
        }
    }

    /**
     * 批量导入
     */
    public function import(){
        ignore_user_abort();
        set_time_limit(0);
        $file = $this->request->file('file');
        if($file){
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix ? $suffix : 'file';
            if (!in_array($suffix, ['xls','xlsx'])){
                $this->error('请上传Excel文件！');
            }
            $path = ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel';
            if(!is_dir($path)){
                mkdir($path,0755,true);
            }
            $info = $file->move($path);
            if($info){
                $logic = new TopicLogic();
                $file_path = ROOT_PATH . 'public/uploads/excel/' . $info->getSaveName();
                $result = $logic->importNew($file_path);
                unlink($file_path);//删除文件
                $msg = '';
                $success = false;
                $rtnData = array();
                switch($result['status']){
                    case 0:
                        $rtnData = $result['error'];
                        $msg = '导入失败！';
                        break;
                    case 1:
                        $success = true;
                        break;
                    case 2:
                        $msg = $result['msg'];
                        break;
                }
                if($success){
                    $this->success('导入成功！');
                }else{
                    $this->error($msg,'',$rtnData);
                }
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }else{
            $this->error('文件不存在！');
        }
    }


    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }
}